//
//  MySubscribeViewController.m
//  BaseProject
//
//  Created by 王洋 on 2020/7/29.
//  Copyright © 2020 王洋. All rights reserved.
//
#import "LSTPopView.h"

#import "MySubscribeCell.h"
#import "MySubscribeSortView.h"
#import "StoreHotelDetailViewController.h"
#import "StoreDetailViewController.h"
#import "EvaluateOrderViewController.h"

#import "MySubscribeViewController.h"

@interface MySubscribeViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) MySubscribeSortView *sortView;
@property (nonatomic, strong) LSTPopView *popView;

@property (nonatomic, strong) UITableView *tableview;

@property (nonatomic, assign) NSInteger pageSize;
@property (nonatomic, assign) NSInteger pageNum;

@property (nonatomic, strong) NSMutableArray <ProClassificationModel *>*classificationDataArray;

@property (nonatomic, strong) NSMutableArray <CommonSubscribeModel *>*dataArray;

@property (nonatomic, assign) NSInteger selctIndex;

@end

@implementation MySubscribeViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self initView];
    self.selctIndex = -1;
    [self request_catData];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self refreshParam];
    [self request_mySubscribeList];
    
}

- (void)refreshParam {
    self.pageSize = 20;
    self.pageNum = 1;
}

- (void)initView {
    
    self.title = @"预约";

    [self.view addSubview:self.tableview];
    
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
    }];
        
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightBtn setTitleColor:UIColorHex(0x333333) forState:UIControlStateNormal];
    [rightBtn setImage:[UIImage imageNamed:@"sub_shaixuan"] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(showCategory) forControlEvents:UIControlEventTouchUpInside];
    rightBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    rightBtn.frame = CGRectMake(0,0,40,30);
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];

    self.navigationItem.rightBarButtonItems =@[rightItem];
}

- (void)showCategory {
        
    WEAKSELF

    self.sortView = [[MySubscribeSortView alloc] initWithArray:self.classificationDataArray.mutableCopy];
    
    self.sortView.MySubscribeSortViewBlock = ^(MySubscribeSortViewActionType type, NSInteger index) {
      
        NSLog(@"out = index = %ld",index);
        switch (type) {
            case MySubscribeSortViewActionType_close:{
                [weakSelf.popView dismiss];
                
            } break;
            case MySubscribeSortViewActionType_select:{
                
                [weakSelf.popView dismiss];

                weakSelf.selctIndex = index;
                NSLog(@"selctIndex = %ld",weakSelf.selctIndex);

                for (ProClassificationModel *model in weakSelf.classificationDataArray) {
                    model.isSelect = NO;
                }
                weakSelf.classificationDataArray[index].isSelect = YES;
                
                [weakSelf refreshParam];
                [weakSelf request_mySubscribeList];
                
            } break;
            default:
                break;
        }
    };
    
    self.sortView.frame = CGRectMake(10, 10, ProductCategoryViewWidth,TTScreenHeight);
    self.sortView.dataArray = self.classificationDataArray;
    self.popView = [LSTPopView initWithCustomView:self.sortView
                                                popStyle:LSTPopStyleSpringFromRight
                                            dismissStyle:LSTDismissStyleSmoothToRight];
    self.popView.hemStyle = LSTHemStyleRight;

    self.popView.popDuration = 0.5;
    self.popView.dismissDuration = 0.5;
    self.popView.isClickFeedback = YES;
    self.popView.bgClickBlock = ^{

        [weakSelf.popView dismiss];
    };

    [self.popView pop];
}

- (NSMutableArray<ProClassificationModel *> *)classificationDataArray {
    if (!_classificationDataArray) {
        _classificationDataArray = @[].mutableCopy;
    }
    return _classificationDataArray;
}

#pragma mark UITableviewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//    return self.dataArray.count;
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 140;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    MySubscribeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MySubscribeCellID"];
    cell.selectionStyle =UITableViewCellSelectionStyleNone;
    [cell fillCellWithModel:self.dataArray[indexPath.row]];
    
    WEAKSELF
    cell.MySubscribeCellBlock = ^(MySubscribeCellActionType type) {
      
        switch (type) {
            case MySubscribeCellActionType_address: {
                [weakSelf gotoMapWithIndex:indexPath.row];
            } break;
            case MySubscribeCellActionType_im: {
                [[TT_IMContactManager manager] ImContactWithStoreId:weakSelf.dataArray[indexPath.row].seller.sellerId];
            } break;
            case MySubscribeCellActionType_call: {
                [[TT_PhonaCallManager manager] callWithStoreId:weakSelf.dataArray[indexPath.row].seller.sellerId];
            } break;
            case MySubscribeCellActionType_evaluate: {

                EvaluateOrderViewController *vc = [[EvaluateOrderViewController alloc] init];
                vc.subscribeModel = weakSelf.dataArray[indexPath.row];
                [weakSelf.navigationController pushViewController:vc animated:YES];
                
            } break;
            default:
                break;
        }
    };
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if ([self.dataArray[indexPath.row].seller.classId isEqualToString:Store_Category_Hotel]) {
        
        StoreHotelDetailViewController *vc = [[StoreHotelDetailViewController alloc] init];
        vc.storeId = self.dataArray[indexPath.row].seller.sellerId;
        [self.navigationController pushViewController:vc animated:YES];
        
    } else {
        StoreDetailViewController *vc = [[StoreDetailViewController alloc] init];
        vc.storeId = self.dataArray[indexPath.row].seller.sellerId;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (UITableView *)tableview {
    if (!_tableview) {
        _tableview = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableview.backgroundColor =  UIColorHex(0xf1f1f1);
        
        _tableview.showsHorizontalScrollIndicator = NO;
        _tableview.showsVerticalScrollIndicator = NO;
        
        _tableview.estimatedSectionHeaderHeight = 0;
        _tableview.estimatedSectionFooterHeight = 0;
        _tableview.estimatedRowHeight = 0;
        
        [_tableview registerNib:[UINib nibWithNibName:@"MySubscribeCell" bundle:nil] forCellReuseIdentifier:@"MySubscribeCellID"];
        
        WEAKSELF
        _tableview.mj_header = [MJRefreshGifHeader headerWithRefreshingBlock:^{
            [weakSelf refreshParam];
            [weakSelf request_mySubscribeList];
        }];
        
    }
    return _tableview;
}

- (NSMutableArray<CommonSubscribeModel *> *)dataArray {
    if (!_dataArray) {
        _dataArray = @[].mutableCopy;
    }
    return _dataArray;
}

#pragma mark - 去地图展示路线
/** 去地图展示路线 */
- (void)gotoMapWithIndex:(NSInteger)index {

    CGFloat latitude  = self.dataArray[index].seller.lat;  // 纬度
    CGFloat longitude = self.dataArray[index].seller.lng; // 经度
    NSString *address = self.dataArray[index].seller.sellerAddress; // 送达地址
    
    [Utilities callMapWithLat:latitude lng:longitude AndAddress:address];
}


- (void)request_mySubscribeList {
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:@(self.pageNum) forKey:@"pageNum"];
    [dic setValue:@(self.pageSize) forKey:@"pageSize"];

    NSMutableDictionary *t = @{}.mutableCopy;
    [t setValue:[TTUserModel sharedObject].userId forKey:@"cdUserId"];
    
    
    NSLog(@"selctIndex = %ld",self.selctIndex);

    if (self.selctIndex>=0 && self.classificationDataArray.count > self.selctIndex) {
        [t setValue:@(self.classificationDataArray[self.selctIndex].scId) forKey:@"classId"];
    }
    
    [dic setValue:t forKey:@"t"];
    
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_MySubscribe];

    WEAKSELF
    [SVProgressHUD showWithStatus:@"正在请求预约列表"];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        [weakSelf.tableview.mj_header endRefreshing];
        [weakSelf.tableview.mj_footer endRefreshing];
        [SVProgressHUD dismiss];
        [[TTNoResultManager shareManager] hideNoResultWithView:weakSelf.tableview];
        
        if ([data isKindOfClass:[NSDictionary class]]) {

            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                NSDictionary *resultDic = [data valueForKey:@"data"];
                if (![resultDic isKindOfClass:[NSDictionary class]]) {
                    return;
                }
                NSArray *list = [resultDic valueForKey:@"list"];
                if ([list isKindOfClass:[NSArray class]]) {
                    if (weakSelf.pageNum == 1) {
                        weakSelf.dataArray = @[].mutableCopy;
                    }
                    for (int i = 0; i < list.count; i++) {
                        NSDictionary *listDic = list[i];
                        NSDictionary *seller = [listDic valueForKey:@"seller"];
                        CommonSubscribeModel *model = [CommonSubscribeModel modelWithDictionary:listDic];
                        model.seller = [CommonSellerModule modelWithDictionary:seller];
                        [weakSelf.dataArray addObject:model];
                    }
                    
                    if (weakSelf.dataArray.count == 0) {
                        [[TTNoResultManager shareManager] showNoResultWithStateInView:weakSelf.tableview errorCode:kTTViewState_EmptyView btnTitle:@"" didPressButton:^{
                        }];
                    }
                    
                    [weakSelf.tableview reloadData];
                }
            }
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        [weakSelf.tableview.mj_header endRefreshing];
        [weakSelf.tableview.mj_footer endRefreshing];
        [SVProgressHUD dismiss];
    }];
    
}

- (void)request_catData {
    NSMutableDictionary *dic = @{}.mutableCopy;

    [dic setValue:@"1" forKey:@"scType"];
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_Category];
    
    WEAKSELF
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {

        if ([data isKindOfClass:[NSDictionary class]]) {

            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                NSDictionary *resultDic = [data valueForKey:@"data"];
                if (![resultDic isKindOfClass:[NSDictionary class]]) {
                    return;
                }
                NSArray *oneList = [resultDic valueForKey:@"sysClassificationList"];
                if ([oneList isKindOfClass:[NSArray class]]) {
                    
                    weakSelf.classificationDataArray = @[].mutableCopy;
                    for (int i = 0; i < oneList.count; i++) {
                        ProClassificationModel *oneModel = [ProClassificationModel modelWithDictionary:oneList[i]];
//                        if (i==0) {
//                            oneModel.isSelect = YES;
//                        }
                            
                        [weakSelf.classificationDataArray addObject:oneModel];
                    }
                }
            }
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {

    }];
}

@end
